<template>
  <LatentProductManage
    title="潜在商品编辑"
    :columns="columns"
    :load-data="getEditList"
    :submit-data="submitEditList"
    @go-back="goBack"
  />
</template>
<script>
import LatentProductManage from './components/LatentProductManage';
import { TABLE_COLUMNS } from './constants/edit';
import { EDIT_UUIDS_KEY, TIPS_COLUMN } from './constants/common';
import { isResponseSuccess, removeSessionByRoute } from '@/utils/bizUtils';
import {
  potentialSearchByUuidsService,
  potentialSaveService
} from '@/api/commodity/temporaryPurchasingGoods/latentProduct';
export default {
  components: {
    LatentProductManage,
  },
  data () {
    return {
      columns: TABLE_COLUMNS
    }
  },
  beforeRouteLeave (to, from, next) {
    if (to.name != this.$route.name) {
      localStorage.removeItem(EDIT_UUIDS_KEY)
    }
    next()
  },
  methods: {
    // 获取编辑列表
    async getEditList (loadingFn) {
      const data = JSON.parse(localStorage.getItem(EDIT_UUIDS_KEY) ?? '[]')
      const res = await potentialSearchByUuidsService(data, loadingFn)
      return res
    },
    // 提交批量编辑集合
    async submitEditList (tableInfo, loadingFn) {
      const data = tableInfo.list
      const res = await potentialSaveService(data, loadingFn)
      const onSuccess = () => {
        this.$message.success('操作成功')
        this.goBack()
      }
      const onFail = echoList => {
        this.$message.warning('有异常原因禁止提交')
        const curColumns = tableInfo.columns.filter(item => item.key != TIPS_COLUMN.key)
        tableInfo.setColumns([
          TIPS_COLUMN,
          ...curColumns
        ])
        tableInfo.setList(echoList)
      }
      if (!isResponseSuccess(res)) return
      const isSuccess = !res?.retData // retData为null是成功
      isSuccess ? onSuccess() : onFail(res.retData)
    },
    // 返回
    goBack () {
      this.$router.push({ name: 'latentProductList' })
    }
  }
}
</script>
